/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.app.imageupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * The Class LocalAnotherServerImageUploadMethod.
 *
 * @author Xi Wei
 */
public class LocalAnotherServerImageUploadMethod implements ImageUploadMethod {

	/* (non-Javadoc)
	 * @see com.xw.app.imageupload.ImageUploadMethod#uploadImage(javax.servlet.http.HttpServletRequest, org.springframework.web.multipart.MultipartFile, java.lang.String, java.lang.String)
	 */
	@Override
	public String uploadImage(HttpServletRequest request, MultipartFile file, String relativePath, String fileName) {
		Properties prop = new Properties();
		try {
			prop.load(getClass().getResourceAsStream("/config.properties"));
			String imageUploadPath = prop.getProperty("image.upload.path");
			String imageAccessUrl = prop.getProperty("image.access.url");
			String path = imageUploadPath + "/" + relativePath;

			File pathFile = new File(path);
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}
			FileCopyUtils.copy(file.getBytes(), new File(path + "/" + fileName));

			String accessUrl = imageAccessUrl + "/" + relativePath + "/" + fileName;
			return accessUrl;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see com.xw.app.imageupload.ImageUploadMethod#uploadImage(javax.servlet.http.HttpServletRequest, java.io.InputStream, java.lang.String, java.lang.String)
	 */
	@Override
	public String uploadImage(HttpServletRequest request, InputStream is, String relativePath, String fileName) {
		Properties prop = new Properties();
		try {
			prop.load(getClass().getResourceAsStream("/application.properties"));
			String imageUploadPath = prop.getProperty("image.upload.path");
			String imageAccessUrl = prop.getProperty("image.access.url");
			String path = imageUploadPath + "/" + relativePath;

			File pathFile = new File(path);
			if (!pathFile.exists()) {
				pathFile.mkdirs();
			}
			FileCopyUtils.copy(is, new FileOutputStream(new File(path + "/" + fileName)));

			String accessUrl = imageAccessUrl + "/" + relativePath + "/" + fileName;
			return accessUrl;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

}
